package cn.itcast.util;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 区间查询
 */
public class HbaseUtil {
    //获取连接对象，全局的，不会关闭连接
    private static Connection conn=null;
    static {
        Configuration configuration = HBaseConfiguration.create();
        configuration.set("hbase.zookeeper.quorum","node01:2181");
        try {
            conn = ConnectionFactory.createConnection(configuration);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询
     */
    public static List<String> scanQuery(String tableName,String family,String colName,String startKey,String endKey){
        ArrayList<String> list = new ArrayList<>();
        Table table = null;
        try {
            table = conn.getTable(TableName.valueOf(tableName));
            Scan scan = new Scan(startKey.getBytes(), endKey.getBytes());
            ResultScanner scanner = table.getScanner(scan);
            for (Result result : scanner) {
                list.add(new String(result.getValue(family.getBytes(), colName.getBytes())));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(table!=null){
                try {
                    table.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return list;
    }

    public static void main(String[] args) {
        List<String> list = scanQuery("quot_stock", "info", "data", "60035420220515160744", "60035420220515160804");
        System.out.println(list);
    }
}
